Parsing Form Data
This code demonstrates how to use busboy to parse form data, including file uploads, from an HTTP POST request.
const Busboy = require('busboy');
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
file.on('data', (data) => {
console.log(`File [${fieldname}] got ${data.length} bytes`);
});
file.on('end', () => {
console.log(`File [${fieldname}] Finished`);
});
});
busboy.on('field', (fieldname, val) => {
console.log(`Field [${fieldname}]: value: ${val}`);
});
busboy.on('finish', () => {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
req.pipe(busboy);
} else {
res.writeHead(404);
res.end();
}
}).listen(8000, () => {
console.log('Listening for requests');
});
Handling File Uploads
This code demonstrates how to handle file uploads using busboy by saving the uploaded files to a specified directory.
const Busboy = require('busboy');
const fs = require('fs');
const path = require('path');
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename) => {
const saveTo = path.join(__dirname, 'uploads', path.basename(filename));
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', () => {
res.writeHead(200, { 'Connection': 'close' });
res.end('Upload complete');
});
req.pipe(busboy);
} else {
res.writeHead(404);
res.end();
}
}).listen(8000, () => {
console.log('Listening for requests');
});